package com.android.topview.watermelon.account.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.topview.watermelon.R
import com.android.topview.watermelon.account.viewmodel.AccountViewModel
import com.android.topview.watermelon.account.adapter.AccountRecyclerAdapter
import com.android.topview.watermelon.account.entity.Account
import com.android.topview.watermelon.application.appContext
import kotlinx.android.synthetic.main.fragment_income.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class IncomeFragment : BaseListFragment() {
    private lateinit var mVpAccount: AccountViewModel
    private var mAdapter: AccountRecyclerAdapter? = null
    var mList: List<Account> = ArrayList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_income, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        initListener()
    }

    private fun initListener() {
        val layoutManager = LinearLayoutManager(appContext)
        rv_income.layoutManager = layoutManager
        mAdapter = AccountRecyclerAdapter(mList,this)
        rv_income.adapter = mAdapter

    }

    private fun initData() {
        mVpAccount = ViewModelProvider(requireActivity()).get(AccountViewModel::class.java)
        mVpAccount.incomeListLiveData.observe(viewLifecycleOwner, Observer { list ->
            run {
                mAdapter?.list = list
                mAdapter?.notifyDataSetChanged()
            }
        })
        launch(Dispatchers.IO) { mVpAccount.getIncomesLiveData() }

    }

    override fun longClick(view: View, position: Int) {
        super.longClick(view, position)
        launch (Dispatchers.IO){
            mAdapter?.list?.get(position)?.let { mVpAccount.deleteAccount(it) }
            mAdapter?.removeItem(position)
        }
    }

    companion object {
        @JvmStatic
        fun newInstance() = IncomeFragment()
    }
}